package com.citcc.api.netty.xc.xchandle;

import java.net.InetSocketAddress;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleState;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citcc.api.netty.server.ChannelMap;
import com.citcc.api.netty.server.TerminalAddressMap;
import com.github.pagehelper.util.StringUtil;






public class XcHeartBeatHandler extends IdleStateAwareChannelHandler{
	private Logger log = LoggerFactory.getLogger(XcHeartBeatHandler.class);
    @Override
    public  void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception {
        assert evt.getState() == IdleState.READER_IDLE;
        readTimedOut(ctx);
    }
 
    

	/**
     * Is called when a read timeout was detected.
     */
    protected void readTimedOut(ChannelHandlerContext ctx) throws Exception {
        if (true) {
            //ctx.getChannel().close();
            //closed = true;
        	InetSocketAddress address = (InetSocketAddress)ctx.getChannel().getRemoteAddress();
            int port = address.getPort(); //得到的是客户端绑定的port
            String add = address.getAddress().toString();
            String req = add+":"+port;
            String terminalNo = TerminalAddressMap.getTerminalNoByAdd(req);
            if(StringUtil.isNotEmpty(terminalNo)){
            	log.info("请求地址:"+req+"-->设备号:"+terminalNo+"-->20秒内未收到客户端数据");
            	TerminalAddressMap.removeTerminalNoByName(req);
            	ChannelMap.removeChannelByName(terminalNo);
            }
        }
    }

}
